import  {FilterXSS}  from "xss";
// 创建一个自定义的XSS过滤器实例，扩展了对Markdown标签的支持
const xssFilterHtml = new FilterXSS({
    whiteList: {
        h1:  ['style',"class"]  ,
        h2:  ['style',"class"]  ,
        h3:  ['style',"class"]  ,
        h4:  ['style',"class"]  ,
        h5:  ['style',"class"]  ,
        h6:  ['style',"class"]  ,
        span:  ['style',"class"]  ,
        p: ['class'],
        em:  ['style',"class"]  ,
        strong:  ['style',"class"]  ,
        a: ['href', 'title'], // 允许 href 和 title 属性
        ul:  ['style',"class"]  ,
        ol:  ['style',"class"]  ,
        li:  ['style',"class"]  ,
        code: ['class','language'],
        pre:  ['style',"class"]  ,
        img: ['src', 'alt'], // 添加 img 标签及其 src 和 alt 属性
        blockquote:  ['style',"class"]  ,
        br:  ['style',"class"]  ,
        hr:  ['style',"class"]  ,
        table: ['border','style',"class"], // 添加表格标签及其 border 属性
        thead:  ['style',"class"]  ,
        tbody:  ['style',"class"]  ,
        tr:  ['style',"class"]  ,
        th:  ['style',"class"]  ,
        td:  ['style',"class"]  ,
        del:  ['style',"class"]  ,
        ins: ['style',"class"]  ,    
        figure: ['style',"class"]  ,  
      },
    css: false 
}) 

export const sanitize = (html: string) => {
  const mdCodeBlockRegex = /```[\s\S]*?```/g;
  const mdCodeBlocks: string[] = [];
  // 先提取 Markdown 代码块
  const sanitizedHtml = html.replace(mdCodeBlockRegex, (match) => {
    mdCodeBlocks.push(match);
    return `passlink ${mdCodeBlocks.length - 1} passlink`;
  });

  // 进行 XSS 过滤，但跳过代码块内的内容
  const resultHtml = xssFilterHtml.process(sanitizedHtml);

  // 将 Markdown 代码块插入回过滤后的 HTML
  const finalHtml = resultHtml.replace(/passlink (\d+) passlink/g, (_match: any, index: any) => {
    return mdCodeBlocks[Number(index)];
  });

  return finalHtml;
};
  

  